import Web3 from 'web3';
import { promises as fs } from 'fs';
// 测试 erc20 代币的 balanceOf 和 transfer 方法 

const jsonData = await fs.readFile('./build/contracts/AdventureLayerTransfer.json', 'utf-8');
const bridgeJson = JSON.parse(jsonData);
const bridgeAbi = bridgeJson.abi;
//console.log(bridgeAbi);

// 配置参数
// account7
 const USER_ADDRESS = '0x4C59A2AA9F39554b9f8D474d70AA3A7cB2467771'; // 你的钱包地址
 const PRIVATE_KEY = '0x7196e384031bb4f6e3647ee2166c574c758e44c4c79907d23ac5a602a96f3340'; // 你的钱包私钥

// account1

// 从一个私钥地址给当前的 USER_ADDRESS 转账 token
const SENDER_PRIVATE_KEY = '0x7fd651a63dcca634d0b527bde1b96f1d2ee246af361f03f951723db27e24e54c'; // 替换为发送者的私钥
const SENDER_ADDRESS = '0xa659f022cb8d0Df682C327d2f16B6f2f41AD2aeA'; // 替换为发送者的地址


const RPC_URL = 'http://[::1]:8545'; // 你的以太坊节点RPC URL
const BRIDGE_CONTRACT_ADDRESS = '0x43F0FFCA27B26dCfA02fce8cA5D97F2F85CbF3fa'; // L1Bridge 合约地址


const TOKEN_CONTRACT_ADDRESS = '0xE8b68A74D8527e650E144BfeCD999302b676DF2f'; // ERC20 代币合约地址

// Web3 设置
const web3 = new Web3(RPC_URL);

// 后续的 Web3 合约和交易操作
console.log('Web3 已成功连接:', web3.currentProvider.host);

// 代币 ABI 和 L1Bridge 合约 ABI
// const bridgeAbi = [
//     { "constant": false, "inputs": [{ "name": "amount", "type": "uint256" }], "name": "deposit", "outputs": [], "type": "function" },
//     { "anonymous": false, "inputs": [{ "indexed": true, "name": "user", "type": "address" }, { "indexed": false, "name": "amount", "type": "uint256" }, { "indexed": false, "name": "timestamp", "type": "uint256" }], "name": "Deposit", "type": "event" }
// ];

const erc20Abi = [
    { "constant": true, "inputs": [{ "name": "owner", "type": "address" }], "name": "balanceOf", "outputs": [{ "name": "", "type": "uint256" }], "type": "function" },
    { "constant": false, "inputs": [{ "name": "spender", "type": "address" }, { "name": "amount", "type": "uint256" }], "name": "approve", "outputs": [{ "name": "", "type": "bool" }], "type": "function" },
    { "constant": true, "inputs": [{ "name": "owner", "type": "address" }, { "name": "spender", "type": "address" }], "name": "allowance", "outputs": [{ "name": "", "type": "uint256" }], "type": "function" },
    {
        constant: false,
        inputs: [
            { name: '_to', type: 'address' },
            { name: '_value', type: 'uint256' }
        ],
        name: 'transfer',
        outputs: [{ name: '', type: 'bool' }],
        type: 'function'
    }
];

async function main() {
    try {
        // 创建钱包签名者
        const account = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY);
        web3.eth.accounts.wallet.add(account);
        web3.eth.defaultAccount = account.address;

        // 验证 TOKEN 合约是否存在
        const tokenCode = await web3.eth.getCode(TOKEN_CONTRACT_ADDRESS);
        console.log('Token合约地址:', TOKEN_CONTRACT_ADDRESS);
        console.log('Token合约代码长度:', tokenCode.length);
        // if (tokenCode === '0x' || tokenCode === '0x0') {
        //     throw new Error(`地址 ${TOKEN_CONTRACT_ADDRESS} 上没有合约代码`);
        // }

        // 创建 ERC20 代币合约实例
        const tokenContract = new web3.eth.Contract(erc20Abi, TOKEN_CONTRACT_ADDRESS);

        // 尝试调用 balanceOf
        try {
            const balance = await tokenContract.methods.balanceOf(USER_ADDRESS).call();
            console.log(`当前余额: ${web3.utils.fromWei(balance, 'ether')} Tokens`);
        } catch (error) {
            console.error('调用 balanceOf 失败:', error);
            throw error;
        }



        // 创建发送者钱包签名者
        const senderAccount = web3.eth.accounts.privateKeyToAccount(SENDER_PRIVATE_KEY);
        web3.eth.accounts.wallet.add(senderAccount);

        // 转账 token
        const transferAmount = web3.utils.toWei('99', 'ether'); // 替换为你想要转账的 token 数量
        const transferTx = tokenContract.methods.transfer(USER_ADDRESS, transferAmount);

        // 获取 gas 估算
        const gas = await transferTx.estimateGas({ from: SENDER_ADDRESS });
        const gasPrice = await web3.eth.getGasPrice();

        // 创建交易对象
        const tx = {
            from: SENDER_ADDRESS,
            to: TOKEN_CONTRACT_ADDRESS,
            gas: gas,
            gasPrice: gasPrice,
            data: transferTx.encodeABI()
        };

        // 签名交易
        const signedTx = await web3.eth.accounts.signTransaction(tx, SENDER_PRIVATE_KEY);

        // 发送交易
        const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
        console.log('转账成功，交易哈希:', receipt.transactionHash);


        // 尝试调用 balanceOf
        try {
            const balance = await tokenContract.methods.balanceOf(USER_ADDRESS).call();
            console.log(`当前余额: ${web3.utils.fromWei(balance, 'ether')} Tokens`);
        } catch (error) {
            console.error('调用 balanceOf 失败:', error);
            throw error;
        }



    } catch (error) {
        console.error("发生错误:", error);
        process.exit(1);
    }
}

main().catch(error => {
    console.error("发生错误:", error);
    process.exit(1);
});
